package com.dinadi.yidi.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.RefundRequestGridAdapter;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.OrderDetailsBean;
import com.dinadi.yidi.bean.UpdateHeadImgBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.http.interfaces.UpdateHeadImgInterface;
import com.dinadi.yidi.ui.view.MyGridView;
import com.dinadi.yidi.ui.view.PickerView;
import com.dinadi.yidi.utils.BitmapChangeBase64Utils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.dinadi.yidi.utils.UtilPopupWindow;
import com.foamtrace.photopicker.ImageCaptureManager;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

/**
 * author: JiaYu.He
 * Date: 2017/9/5   申请退款
 * Time: 10:50
 */
public class RefundRequestActivity extends BaseActivity {
    private static final int REQUEST_CAMERA_CODE = 11;
    private static final int REQUEST_PREVIEW_CODE = 22;
    private View view;
    private TextView tvTitle;
    private RelativeLayout select_refund_reason, layout_other_reasons;
    private UtilPopupWindow popupWindow;
    private TextView refund_reason;
    private MyGridView gridView;
    private ImageView img_submit_apply;
    private EditText edit_other_reasons;
    private RefundRequestGridAdapter gridAdapter;
    private String refundReason;
    private ArrayList<String> imagePaths = new ArrayList<>(10);
    private ArrayList<String> imageNums = new ArrayList<>(10);
    private ArrayList<String> pathList = new ArrayList<>(10);

    private ImageCaptureManager captureManager; // 相机拍照处理类
    private String userID, token, orderId, imgs;
    private int refundCause;
    private StringBuilder sb;
    private int a = 0;
    private int b = 0;


    @Override
    protected View getLayout() {
        view = LayoutInflater.from(RefundRequestActivity.this).inflate(R.layout.activity_refund_request, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        tvTitle.setText(R.string.text_refund_request);
        select_refund_reason = (RelativeLayout) view.findViewById(R.id.select_refund_reason);
        refund_reason = (TextView) view.findViewById(R.id.refund_reason);
        layout_other_reasons = (RelativeLayout) view.findViewById(R.id.layout_other_reasons);
        gridView = (MyGridView) view.findViewById(R.id.gridView);
        captureManager = new ImageCaptureManager(RefundRequestActivity.this);
        img_submit_apply = (ImageView) view.findViewById(R.id.img_submit_apply);
        edit_other_reasons = (EditText) view.findViewById(R.id.edit_other_reasons);

        gridAdapter = new RefundRequestGridAdapter(RefundRequestActivity.this, imagePaths);
        gridView.setAdapter(gridAdapter);
        // preview
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imagePaths.size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(RefundRequestActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(6); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(RefundRequestActivity.this);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }

            }
        });
        sb = new StringBuilder();
    }

    @Override
    public void onResume() {
        super.onResume();
        String isRefresh = SharePreferencesHelper.getInstance(RefundRequestActivity.this).getString("isRefresh");
        if ("yes".equals(isRefresh)) {
            userID = SharePreferencesHelper.getInstance(RefundRequestActivity.this).getString("userId");
            token = SharePreferencesHelper.getInstance(RefundRequestActivity.this).getString("token");
            SharePreferencesHelper.getInstance(RefundRequestActivity.this).putString("isRefresh", "no");
        }
    }

    @Override
    protected void initListener() {
        registerClickListener(select_refund_reason, img_submit_apply);
    }

    @Override
    protected void initData() {
  /*用户ID*/
        userID = SharePreferencesHelper.getInstance(RefundRequestActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(RefundRequestActivity.this).getString("token");
        Intent intent = getIntent();
        orderId = intent.getStringExtra("orderId");
    }

    @Override
    protected void clickEvent(View v) {

        switch (v.getId()) {
            case R.id.select_refund_reason:
                reasonsForRefund();
                break;
            case R.id.img_submit_apply:
                // 进行点击事件后的逻辑操作
                  /*提交申请*/
                if (refund_reason.getText().toString().equals("请选择退款原因")) {
                    ToastUtil.showToast("请选择退款原因");
                } else {
                    uploadImage();
                }
                break;
            default:
                break;
        }
    }

    private void uploadImage() {
        showLoadingDialog("申请退款中");
        if (imagePaths.size() == 0) {
            OrderDetailsBean bean = new OrderDetailsBean();
            bean.setRefundCause(refundCause + "");
            bean.setRefundNote(edit_other_reasons.getText().toString());
            bean.setOrderId(orderId);
            bean.setToken(token);
            CommonInterface orderDetailsInterface = new CommonInterface(RefundRequestActivity.this, refundHttpListener);
            orderDetailsInterface.getInterface("16031", JSON.toJSONString(bean));
        } else {
            for (int i = 0; i < imagePaths.size(); i++) {
                String path = imagePaths.get(i);
                final String fileType = path.substring(path.lastIndexOf(".") + 1);
                pathList.add(fileType);
                Glide.with(RefundRequestActivity.this).load(imagePaths.get(i)).asBitmap().centerCrop().into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        String bitmapImg = BitmapChangeBase64Utils.bitmapToBase64(resource);
                        UpdateHeadImgBean updateBean = new UpdateHeadImgBean();
                        updateBean.setUserId(userID);
                        updateBean.setToken(token);
                        updateBean.setFileType(pathList.get(b));
                        updateBean.setFileName("image_" + a++);
                        updateBean.setFileDesc("图片上传");
                        updateBean.setFileBase64Content(bitmapImg);
                        UpdateHeadImgInterface updateHeadImgInterface = new UpdateHeadImgInterface(RefundRequestActivity.this, httpListener2);
                        updateHeadImgInterface.getInterface("15004", updateBean);
                        b = b + 1;
                    }
                }); //方法中设置asBitmap可以设置回调类型
            }
        }


    }


    HttpListener httpListener2 = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                String imgId = JsonUtil.getFieldValue(response, "imgId");
                String imgUrl = JsonUtil.getFieldValue(response, "imgUrl");
                sb.append(imgId + ",");
                imgs = sb.toString();
                imageNums.add(imgs);
                if (imageNums.size() == imagePaths.size()) {
                    OrderDetailsBean bean = new OrderDetailsBean();
                    bean.setRefundCause(refundCause + "");
                    bean.setRefundNote(edit_other_reasons.getText().toString());
                    bean.setImgs(imgs);
                    bean.setOrderId(orderId);
                    bean.setToken(token);
                    CommonInterface orderDetailsInterface = new CommonInterface(RefundRequestActivity.this, refundHttpListener);
                    orderDetailsInterface.getInterface("16031", JSON.toJSONString(bean));
                }

            } else {
                ToastUtil.showToast("上传图片失败");
                closeLoadingDialog();
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            ToastUtil.showToast("上传图片失败");
            closeLoadingDialog();
        }
    };
    HttpListener refundHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                closeLoadingDialog();
                ToastUtil.showToast("提交申请成功");
                SharePreferencesHelper.getInstance(RefundRequestActivity.this).putString("isRefresh", "yes");
                RefundRequestActivity.this.finish();
            } else {
                closeLoadingDialog();
                ToastUtil.showToast(errMsg);

            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            closeLoadingDialog();
            ToastUtil.showToast("申请退款失败");

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();
                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths);
                    }
                    break;

            }
        }
    }

    private void loadAdpater(ArrayList<String> paths) {
        imagePaths.clear();
        gridAdapter.clearDate();
        if (paths != null) {
            imagePaths.addAll(paths);
        }

        try {
            JSONArray obj = new JSONArray(imagePaths);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        gridAdapter.notifyDataSetChanged();
        gridView.invalidateViews();
        gridView.setAdapter(gridAdapter);

    }

    /*选择原因*/
    private void reasonsForRefund() {
        //当然是先初始化popupWindow
        popupWindow = new UtilPopupWindow();
        //我再工具中没有写构造函数，这里调用默认的构造函数
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        final int windowHeight = d.getHeight();
        //弹出框填充布局
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_select_1, null);
        RelativeLayout layout2 = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_refund_request, null);
        popupWindow.setPopupWindow(RefundRequestActivity.this, windowHeight / 3, layout, layout2, Gravity.BOTTOM);

        PickerView picker_view = (PickerView) layout.findViewById(R.id.picker_view);
        final TextView btn_confirm = (TextView) layout.findViewById(R.id.btn_confirm);
        //选择性别
        List<String> data = new ArrayList<String>();
        data.add("不想买了");
        data.add("信息填写错误");
        data.add("重复下单");
        data.add("未收到商品");
        data.add("卖家发错商品");
        data.add("商品缺损");
        data.add("其他");

        picker_view.setData(data);
        //默认
        refundReason = "不想买了";
        picker_view.setSelected(refundReason);

        picker_view.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                //选中的人群
                refundReason = text;
            }
        });
        /*确认选择*/
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refund_reason.setText(refundReason);

                if ("不想买了".equals(refundReason)) {
                    refundCause = 1;
                    layout_other_reasons.setVisibility(View.GONE);
                } else if ("信息填写错误".equals(refundReason)) {
                    refundCause = 2;
                    layout_other_reasons.setVisibility(View.GONE);
                } else if ("重复下单".equals(refundReason)) {
                    refundCause = 3;
                    layout_other_reasons.setVisibility(View.GONE);
                } else if ("未收到商品".equals(refundReason)) {
                    refundCause = 4;
                    layout_other_reasons.setVisibility(View.GONE);
                } else if ("卖家发错商品".equals(refundReason)) {
                    refundCause = 5;
                    layout_other_reasons.setVisibility(View.GONE);
                } else if ("商品缺损".equals(refundReason)) {
                    refundCause = 6;
                    layout_other_reasons.setVisibility(View.GONE);
                } else if ("其他".equals(refundReason)) {
                    refundCause = 7;
                    layout_other_reasons.setVisibility(View.VISIBLE);
                }
                refund_reason.setTextColor(getResources().getColor(R.color.color_333333));
                popupWindow.dismiss();

            }
        });
        TextView btn_cancel = (TextView) layout.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 　　* 将bitmap转换成base64字符串
     * 　　*
     * 　　* @param bitmap
     * 　　* @return base64 字符串
     */
/*    public String bitmaptoString(Bitmap bitmap, int bitmapQuality) {
        // 将Bitmap转换成字符串
        String string = null;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, bitmapQuality, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }*/

}
